<?php

/**
 * 分类管理
 *
 * @author suning <snsnsky@gmail.com>
 */

use \Common\Bridge;

define("SITE_AUTH", 'shop-cate');

require '../../../common.inc.php';

class cate extends lib\core\AdminAction
{
    private $pdo_r;
    private $list_url = '/data/modules/shop/cate.php';


    public function doDefault()
    {
        $cate = self::getAllCate();
        $page = $this->app->page();
        $page->value("cate", $cate);
        $page->output('shop/cate.tpl');
    }

    public function doAddCate()
    {
        $dbr = Bridge::pdo(Bridge::DB_CENTER_W);

        $new['Name'] = strval($_POST['Name']);
        $new['Sort'] = intval($_POST['Sort']);

        $id = intval($_POST['Id']);

        if ($id == 0)
        {
            //同名分类验证
            $cate_check = $dbr->query("select * from Category where `Name`='{$new['Name']}'")->fetch();
            if (!empty($cate_check))
            {
                self::output(['title'=>'已存在此分类','type'=>'error']);
            }
            if (trim($_POST['Url'])) {
                $new['IconUrl'] = trim($_POST['Url']);
            }
//            $re = $dbr->insert('Category', $new);
            $re = \Center\Category::add($new);
            $this->adminLog('添加分类', $re, 'add', serialize($new));
        }
        else
        {
            //上传图片
//            $img = $_FILES['Cover'];
//            if (isset($img['name']) && $img['error'] == 0 && $img['size'] > 0) {
//                // 复制图片
//                $imgUrlAddre = self::saveImageUrl($id, $_FILES['Cover']);
//                $new['IconUrl'] = $imgUrlAddre;
//            }
            //更新
//            $re = $dbr->update('Category', $new, ['Id'=>$id]);//
            $new['IconUrl'] = trim($_POST['IconUrl']);
            $re = \Center\Category::update($id, $new);//
            $this->adminLog('更新分类', $id, 'update', serialize($new));
        }

        if ($re !== false)
        {
            self::output(['title'=>'操作成功','type'=>'success']);
        } else {
            self::output(['title'=>'操作失败','type'=>'error']);
        }
    }


    public function doDelCate()
    {
        $id = intval($_GET['id']);

        $re = \Center\Category::delete($id);
        if ($re !== false)
        {
            $this->adminLog('删除分类', $id, 'del', $id);
            HDshowMsg('删除成功！', ['type' => 'success', 'url' => $this->list_url]);
        }
        HDshowMsg('删除失败！', ['type' => 'error', 'url' => $this->list_url]);
    }

    public static  function getAllCate()
    {
        $db = Bridge::pdo(Bridge::DB_CENTER_W);
        $data = $db->query("select * from Category where ParentId=0 order by Sort desc")->fetchAll();
        empty($data) && $first = [];
        $return = [];
        foreach ($data as $v)
        {
            $id = $v['Id'];
            if ($v['IconUrl']) {
                $v['IconUrl'] = str_replace('.jpg', '_100.jpg', $v['IconUrl']);
            }
            $return[$id] = $v;
        }
        return $return;
    }

    /**
     *
     */
    public function doEdit()
    {
        $id = (int)$_GET['id'];
        if ($id < 1) {
            HDshowMsg('操作失败！', ['type' => 'error', 'desc' => 'Id为空']);
        }

        $sql = "SELECT * FROM Category WHERE Id = $id";
        $list = $this->readDb($sql);

        $smarty = $this->app->page();
        $data = current($list);
        $smarty->value('info', $data);
        $smarty->output('shop/cateedit.tpl');
    }


    /**
     * 利用SQL语句读取数据库并返回相应数据
     *
     * @param $sql
     * @return mixed
     */
    private function readDb($sql)
    {
        $pdo = $this->pdo_r;
        if (empty($pdo)) {
            $pdo = $this->pdo_r = Bridge::pdo(Bridge::DB_CENTER_W);
        }

        $obj = $pdo->query($sql);

        return $obj->fetchAll();
    }

    /**
     * @param $filename
     * @return bool|string
     */
//    private static function saveImageUrl($id, $filename)
//    {
//        ///
//        $upload_dir = \Common\ResourcePathManager::getCateIconSavePath();
//
//        $hash = \Common\PhotoImage::getImageHash($id);
//        //$src_img = $upload_dir . $hash['hash1'] . "/" . $hash['hash2'] . "/" . $id . ".jpg";
//        $image_status = \Common\PhotoImage::checkImage($filename);
//
//        if ($image_status['code'] == 4) {
//            $image_status = \Common\PhotoImage::checkImageByUrl($filename);
//
//            if ($image_status['code'] == 4) {
//                return false;
//            }
//        }
//        $ext = $image_status['image_type'];
//
//        //配置图片上传目录
//        $cfg = [
//            'base' => $upload_dir,
//            'thumb' => [
//                'source' => [
//                    'url' => '{hash1}/{hash2}/{id}.{ext}'
//                ],
//                '100' => [
//                    'width' => 100,
//                    'height' => 100,
//                    'position' => 'middle',
//                    'watermark' => false,
//                    'url' => '{hash1}/{hash2}/{id}_100.{ext}'
//                ],
//                '300' => [
//                    'width' => 300,
//                    'position' => 'middle',
//                    'watermark' => false,
//                    'url' => '{hash1}/{hash2}/{id}_300.{ext}'
//                ],
//                '800' => [
//                    'width' => 800,
//                    'position' => 'middle',
//                    'watermark' => false,
//                    'url' => '{hash1}/{hash2}/{id}_800.{ext}'
//                ]
//            ],
//            'hash1' => $hash['hash1'],
//            'hash2' => $hash['hash2'],
//            'ext' => $ext,
//            'id' => $id
//        ];
//
//        if ($image_status['status'] == true) {
//            $result = \Common\PhotoImage::imageResize($cfg, $image_status);
//
//            if ($result) {
//                $res_arr = [
//                    "http://img.jinguonet.com/cate/" . $hash['hash1'] . "/" . $hash['hash2'] . "/" . $id . "." . $ext,
//                    "http://img.jinguonet.com/cate/" . $hash['hash1'] . "/" . $hash['hash2'] . "/" . $id . "_100." . $ext,
//                    "http://img.jinguonet.com/cate/" . $hash['hash1'] . "/" . $hash['hash2'] . "/" . $id . "_300." . $ext,
//                    "http://img.jinguonet.com/cate/" . $hash['hash1'] . "/" . $hash['hash2'] . "/" . $id . "_800." . $ext,
//                ];
//
//                return "http://img.jinguonet.com/cate/" . $hash['hash1'] . "/" . $hash['hash2'] . "/" . $id . "." . $ext . "?v=" . time();
//            }
//        }
//
//        return false;
//    }
}


$app->run();
